<template>
  <div class="app-container app-content">
    <el-row class="line-bottom" v-show="showSearch">
      <el-col class="form_col">
        <el-form :model="queryParams" ref="queryForm" :size="formItemSize" v-show="showSearch"
                 :label-width="labelWidth">
          <div id="searchFilter" style="display: flex; flex-wrap: wrap">
            <el-form-item label="用户名称" prop="userName">
              <el-input
                  v-model="queryParams.userName"
                  placeholder="请输入用户名称"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="用户编号" prop="userId">
              <el-input
                  v-model="queryParams.userId"
                  placeholder="请输入用户编号"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="所属客户" prop="tenantId">
              <el-select filterable v-model="queryParams.tenantId" placeholder="请选择所属客户" style="width: 100%">
                <el-option
                  v-for="dept in deptOption"
                  :key="dept.tenantId"
                  :label="dept.deptName"
                  :value="dept.tenantId"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
      </el-col>

      <el-col class="form_query">
        <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
        </el-button>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['basedata:usersxb:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['basedata:usersxb:remove']"
        >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-has-permi="['basedata:userxb:import']"
        >导入
        </el-button>
      </el-col>

      <RightDropdown :columns="columns" :showSearch.sync="showSearch" :uploadVisible="uploadVisible"
                     @queryTable="getList" @export="handleExport" @upload="handleUpload"
                     :hasPermiExport="['basedata:usersxb:export']"></RightDropdown>
    </el-row>

    <el-table v-loading="loading" :data="usersxbList" size="mini" row-key="id" border :height="getAvailableHeight"
              @selection-change="handleSelectionChange" default-expand-all
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}" :default-sort="defaultSort"
              @sort-change="handleSorterChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="所属客户" align="center" prop="deptName" v-if="columns[9].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="用户编号" align="center" prop="userId" v-if="columns[0].visible"
                       :show-overflow-tooltip="true" sortable="custom"
                       :sort-orders="['ascending', 'descending']"/>
      <el-table-column label="用户名称" align="center" prop="userName" v-if="columns[1].visible"
                       :show-overflow-tooltip="true" sortable="custom"
                       :sort-orders="['ascending', 'descending']"/>
      <el-table-column label="用户手机号码" align="center" prop="userPhone" width="130" v-if="columns[2].visible"
                       :show-overflow-tooltip="true" sortable="custom"
                       :sort-orders="['ascending', 'descending']"/>
      <el-table-column label="证件类型" align="center" prop="idType" v-if="columns[3].visible"
                       :show-overflow-tooltip="true" sortable="custom"
                       :sort-orders="['ascending', 'descending']"/>
      <el-table-column label="证件号码" align="center" prop="userCode" v-if="columns[4].visible"
                       :show-overflow-tooltip="true" sortable="custom"
                       :sort-orders="['ascending', 'descending']"/>
      <el-table-column label="用户通讯地址" align="center" prop="userAddress" width="140" v-if="columns[5].visible"
                       :show-overflow-tooltip="true" sortable="custom"
                       :sort-orders="['ascending', 'descending']"/>
      <el-table-column label="备注" align="center" prop="remark" v-if="columns[6].visible"
                       :show-overflow-tooltip="true" sortable="custom"
                       :sort-orders="['ascending', 'descending']"/>
      <el-table-column label="用户状态" align="center" prop="userMark" v-if="columns[7].visible"
                       :show-overflow-tooltip="true" sortable="custom"
                       :sort-orders="['ascending', 'descending']">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user_status" :value="scope.row.userMark"/>
        </template>
      </el-table-column>
      <el-table-column label="立户时间" align="center" prop="createTime" v-if="columns[8].visible"
                       :show-overflow-tooltip="true" sortable="custom"
                       :sort-orders="['ascending', 'descending']">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="修改" placement="top">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basedata:usersxb:edit']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basedata:usersxb:remove']"
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改区域管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户编号" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户编号"/>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名称"/>
        </el-form-item>
        <el-form-item label="所属客户" prop="tenantId">
          <el-select filterable v-model="form.tenantId" placeholder="请选择所属客户" style="width: 100%;">
            <el-option
              v-for="dept in deptOption"
              :key="dept.tenantId"
              :label="dept.deptName"
              :value="dept.tenantId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="userPhone">
          <el-input v-model="form.userPhone" placeholder="请输入用户手机号码"/>
        </el-form-item>
        <el-form-item label="证件类型" prop="idType">
          <el-input v-model="form.idType" placeholder="请输入证件类型"/>
        </el-form-item>
        <el-form-item label="证件号码" prop="userCode">
          <el-input v-model="form.userCode" placeholder="请输入证件号码"/>
        </el-form-item>
        <el-form-item label="用户通讯地址" prop="userAddress">
          <el-input v-model="form.userAddress" placeholder="请输入用户通讯地址"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
        <el-form-item label="用户状态" prop="userMark">
          <el-select v-model="form.userMark" placeholder="请选择用户状态" style="width: 100%;">
            <el-option v-for="dict in dict.type.user_status" :key="dict.value" :label="dict.label"
                       :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptList } from '@/api/system/dept.js'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listUsersxb, getUsersxb, delUsersxb, addUsersxb, updateUsersxb} from "@/api/record/usersxb";
import {getToken} from "@/utils/auth";

export default {
  name: "TerminalUsers",
  components: {Treeselect},
  dicts: ['yes_no', 'belong_department', 'user_status'],
  data() {
    return {
      // 客户下拉框中的数据
      deptOption: [],
      screenHeight: null,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 区域管理表格数据
      usersxbList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        userName: null,
        userId: null,
        tenantId: null,
      },
      ids: [],
      // 列信息
      columns: [
        {key: 0, label: `用户编号`, visible: true},
        {key: 1, label: `用户名称`, visible: true},
        {key: 2, label: `用户手机号码`, visible: true},
        {key: 3, label: `证件类型`, visible: true},
        {key: 4, label: `证件号码`, visible: true},
        {key: 5, label: `用户通讯地址`, visible: true},
        {key: 6, label: `备注`, visible: true},
        {key: 7, label: `用户状态`, visible: true},
        {key: 8, label: `立户时间`, visible: true},
        {key: 9, label: `所属客户`, visible: true},
      ],
      // 默认排序
      defaultSort: {prop: 'createTime', order: 'descending'},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          {required: true, message: "请选择父级区域", trigger: "change"}
        ],
        userId: [
          {required: true, message: "请输入用户编号", trigger: "blur"}
        ],
        userName: [
          {required: true, message: "请输入用户名称", trigger: "blur"}
        ],
        tenantId: [
          {required: true, message: "请选择所属客户", trigger: "change"}
        ],
      },
      maxShow: 4,
      formItemSize: 'mini',
      collapseAble: false,
      fold: false,
      labelWidth: '80px',
      uploadVisible: true,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basedata/usersxb/importData"
      },
    };
  },
  created() {
    this.getList();
    this.screenHeight = document.body.clientHeight
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - (this.showSearch ? 240 : 195)
    },
  },
  methods: {
    // 获取所有客户
    getDeptList() {
      deptList().then(response => {
        this.deptOption = response.data
      })
    },
    /** 排序触发事件 */
    handleSorterChange({column, prop, order}) {
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order
      this.getList()
    },
    /** 检查设置排序字段 */
    checkSortColumn() {
      if (!this.queryParams.orderByColumn) {
        this.queryParams.orderByColumn = this.defaultSort.prop
        this.queryParams.isAsc = this.defaultSort.order
      }
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户档案导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 查询区域管理列表 */
    getList() {
      this.checkSortColumn()
      this.loading = true;
      listUsersxb(this.queryParams).then(response => {
        this.usersxbList = response.rows;
        this.total = response.total
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        userName: null,
        userPhone: null,
        idType: null,
        userCode: null,
        userAddress: null,
        remark: null,
        userMark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row) {
        this.form.parentId = row.id
      }
      this.open = true;
      this.title = "添加用户管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getUsersxb(id).then(response => {
        this.form = response.data;
        // this.form.parentId = (response.data.parentId === 'root' ? undefined : response.data.parentId)
        this.open = true;
        this.title = "修改用户管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUsersxb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUsersxb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.id || this.ids
      this.$modal.confirm('是否确认删除所选记录？').then(function () {
        return delUsersxb(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basedata/usersxb/export', {
        ...this.queryParams
      }, `区域信息.xlsx`)
    },
    // 下载模板
    handleUpload() {
      this.download('basedata/usersxb/getImportTemplate', {}, `用户档案模板.xlsx`)
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.formItemSize}`)
      const len = group?.length ? group?.length : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    }
  },
  mounted() {
    this.getDeptList();
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
};
</script>
<style scoped lang="scss">
.form_col {
  width: 80%;

  ::v-deep .el-form {
    width: 100%;
  }

  ::v-deep .el-form-item {
    width: 18%;
  }
}

.form_query {
  width: 20%;
  text-align: right;
}
</style>
